<template>
  <el-upload
    :data = "dataObj"
    :multiple="multiple"
    :headers="headers"
    :on-success="handleImageSuccess"
    :on-progress="handleUploadProgress"
    :on-remove="handleUploadRemove"
    :http-request="handleUploadRequest"
    :action="action"
    :accept="accept"
    :file-list="fileList">
    <el-button size="small" type="primary">点击上传</el-button>
  </el-upload>
</template>

<script>
import { getToken } from '@/utils/auth'
import upload from '@/utils/cos'
import createUniqueString from '@/utils/createUniqueString'


export default {
  name: 'Cosupload',
  props: {
    value: {
      type: String|Number,
      default: 0
    },
    accept: {
      type: String,
      default: 'audio/mp4, video/mp4'
    },
    multiple: {
      type: Boolean,
      default: false
    },
    imagelist: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      action: process.env.BASE_API + '/upload/chunk',
      dataObj: {},
      percentage: 0,
      headers: {
        'X-Token': getToken()
      },
      fileList: this.imagelist ? this.imagelist : [],
      tmp: ''
    }
  },
  watch: {
    fileList: function(fileList, oldFileList) {
      let id = 0
      if (fileList.length > 0) {
        for (const item of fileList) {
          // console.log(item)
          if (item.response) {
            id = item.response.data.id
          } else if (item.id) {
            id = item.id
          }
        }
      }
      this.emitInput(id)
    },
    imagelist: function(newFileList, oldFileList){
      this.fileList = newFileList
    }
  },
  methods: {
    handleUploadRequest(options) {
      upload(options, createUniqueString() + '.mp4')
    },
    emitInput(val) {
      this.$emit('input', val)
    },
    handleImageSuccess(response, file, fileList) {
      this.fileList = [file]
      this.$notify({
          title: '成功',
          message: '视频上传成功',
          type: 'success',
          duration: 2000
        })
    },
    handleUploadProgress(event, file, fileList) {
      
    },
    handleUploadRemove(file, fileList) {
      this.fileList = []
    },
    beforeUpload() {
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.image {
  width: 100%;
  height: 100%;
  display: block;
}
</style>
